# Maintainer: Hoang Nguyen <folliekazetani@protonmail.com>
pkgname=opa
pkgver=0.61.0
pkgrel=5
pkgdesc="Open source, general-purpose policy engine"
url="https://www.openpolicyagent.org/"
# only platforms with full +wasm support, as upstream does
arch=""
license="Apache-2.0"
makedepends="go wasmtime-dev"
checkdepends="tzdata"
subpackages="
	$pkgname-doc
	$pkgname-bash-completion
	$pkgname-fish-completion
	$pkgname-zsh-completion
	"
source="
	$pkgname-$pkgver.tar.gz::https://github.com/open-policy-agent/opa/archive/refs/tags/v$pkgver.tar.gz
	https://dev.alpinelinux.org/archive/open-policy-agent/pr6556-bump-wasmtime-go-v17.patch
	tests-go1.22-compat.patch
	"

export CGO_ENABLED=1
export GOCACHE="${GOCACHE:-"$srcdir/go-cache"}"
export GOTMPDIR="${GOTMPDIR:-"$srcdir"}"
export GOMODCACHE="${GOMODCACHE:-"$srcdir/go"}"

build() {
	# report.ExternalServiceURL is left blank to disable telemetry
	# - "opa version -c" errors out
	# - "opa run" fails the version check process silently in the background
	# this is intended :)
	local goldflags="
	-X github.com/open-policy-agent/opa/version.Version=$pkgver
	-X github.com/open-policy-agent/opa/version.Hostname=AlpineLinux
	-X github.com/open-policy-agent/opa/version.Vcs=0000000000000000000000000000000000000000
	-X github.com/open-policy-agent/opa/version.Timestamp=$(date -u "+%Y-%m-%dT%H:%M:%SZ" ${SOURCE_DATE_EPOCH:+-d @$SOURCE_DATE_EPOCH})
	-X github.com/open-policy-agent/opa/internal/report.ExternalServiceURL=
	"

	export CGO_CFLAGS="$CFLAGS"
	export CGO_LDFLAGS="$LDFLAGS -L/usr/lib -lwasmtime"

	go build -v -ldflags "$goldflags" -tags opa_wasm

	mkdir -p man/
	go run build/generate-man/generate.go man/

	for shell in bash fish zsh; do
		./opa completion $shell > opa.$shell
	done
}

check() {
	# tests are not ran with opa_wasm tag so tests that use wasm engine fail
	go test -skip TestRegoTargetWasmAndTargetPluginDisablesIndexingTopdownStages ./...
}

package() {
	install -Dm755 opa -t "$pkgdir"/usr/bin/

	install -Dm644 man/*.1 -t "$pkgdir"/usr/share/man/man1/

	install -Dm644 opa.bash \
		"$pkgdir"/usr/share/bash-completion/completions/opa
	install -Dm644 opa.fish \
		"$pkgdir"/usr/share/fish/vendor_completions.d/opa.fish
	install -Dm644 opa.zsh \
		"$pkgdir"/usr/share/zsh/site-functions/_opa
}

sha512sums="
d80443cf58d3b703cf4209d4170b76a2173a6af5fc18c2f777d1258b328aa35e030ac220212a03ad76f26ff08c1a93077fccbacf9a3ae6c72f48162b715375a9  opa-0.61.0.tar.gz
458e515e22faf739ef6966ea39de5f7d9863d5d1e1e9b8659dc6e0c717ec03215ffb2770f4d48437bf995ec72fc52d85d9b8b53aa3f8428901b49fe59760a167  pr6556-bump-wasmtime-go-v17.patch
74ab9327d0b7a5ed2c568cd0f4d1e06272671e785112f0037b810c54e2a1bc5437722973e8b4bdc2619570dbf2ae637b2057817c36b7828e365f48d1c0184c9a  tests-go1.22-compat.patch
"
